// import Immutable from 'immutable';

import { NavigationActions } from 'react-navigation'

import { Navigator } from '../containers/app/navigator'

import {
  LOGIN,
  USER_LOGOUT,
  PUSH,
  RESET,
  RESET_SECOND
  // POP
} from '../constants/actionType'

import {
  CENTER
} from '../constants/pages'

// import DB from '../utils/storage'

const firstAction = Navigator.router.getActionForPathAndParams('Home')
const tempNavState = Navigator.router.getStateForAction(firstAction)
// const secondAction = Navigator.router.getActionForPathAndParams('Login')
const navState = Navigator.router.getStateForAction(
  tempNavState
)

const initialState = Navigator.router.getStateForAction(
  // secondAction,
  navState
)

// let initialState
// DB.get('user').then((user) => {
//   console.log('==DB.get(\'user\')==', user)
//   if (user && user.userId) {
//     console.log('===有user==')
//     initialState = Navigator.router.getStateForAction(
//       navState
//     )
//   } else {
//     console.log('===没有user==')
//     initialState = Navigator.router.getStateForAction(
//       secondAction,
//       navState
//     )
//   }
// })

export default (state = initialState, action) => {
  let newState = state
  switch (action.type) {
    case LOGIN:
      console.log('==LOGIN===', action)
      return Navigator.router.getStateForAction(NavigationActions.reset({
        index: 0,
        actions: [
          NavigationActions.navigate({
            routeName: CENTER,
            params: action.payload.params
          })
        ]
      }), newState)
    case USER_LOGOUT:
      console.log('==USER_LOGOUT===', action)
      return Navigator.router.getStateForAction(NavigationActions.reset({
        index: 0,
        actions: [
          NavigationActions.navigate({
            routeName: 'Login',
            params: action.payload.params
          })
        ]
      }), newState)
    case PUSH:
      console.log('==PUSH===', action, action.payload.page)
      return Navigator.router.getStateForAction(NavigationActions.navigate({
        routeName: action.payload.page,
        params: action.payload.params
      }), newState)
    case RESET:
      return Navigator.router.getStateForAction(NavigationActions.reset({
        index: 0,
        actions: [
          NavigationActions.navigate({
            routeName: action.payload.page,
            params: action.payload.params
          })
        ]
      }), newState)
    case RESET_SECOND:
      console.log('==RESET_SECOND===')
      return Navigator.router.getStateForAction(NavigationActions.reset({
        index: 1,
        actions: [
          NavigationActions.navigate({
            routeName: action.payload.pageOne,
            params: action.payload.params
          }),
          NavigationActions.navigate({routeName: action.payload.pageTwo})
        ]
      }), newState)
    default :
      return Navigator.router.getStateForAction(action, state)
  }
}
